
#import "PlayerPlugin.h"
#import "PolyvVideoViewFactory.h"
#import <PLVVodSDK/PLVVodSDK.h>

#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif


@implementation PlayerPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {

    FlutterMethodChannel* channel = [FlutterMethodChannel
        methodChannelWithName:@"plugins.polyv/util"
              binaryMessenger:[registrar messenger]];
    PlayerPlugin* instance = [[PlayerPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
    //注册插件
    [registrar registerViewFactory:[[PolyvVideoViewFactory alloc] initWithMessenger:registrar.messenger] withId:@"plugins.polyv/video"];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"playerConfig" isEqualToString:call.method]) {
      DLog(@"接收到的call.arguments >>>%@",call.arguments);
      NSDictionary *argsMap = call.arguments;
      NSString *_config = argsMap[@"config"];
      NSString *_aesKey = argsMap[@"aesKey"];
      NSString *_iv = argsMap[@"iv"];
      [self initSDKForLiveWithConfig:_config aesKey:_aesKey iv:_iv];
  }
  else if ([@"getFirstImage" isEqualToString:call.method]) {
      // 获取点播首帧封面
      NSDictionary *argsMap = call.arguments;
      NSString *_vid = argsMap[@"vid"];
      if ([@"" isEqualToString:_vid]) result(@"");
      [PLVVodVideo requestVideoWithVid:_vid completion:^(PLVVodVideo *video, NSError *error) {
          result(video.snapshot);
      }];
  }
  else if ([@"accountConfig" isEqualToString:call.method]) {
      NSDictionary *argsMap = call.arguments;
      NSString *userID = argsMap[@"userID"];
      NSString *secretKey = argsMap[@"secretKey"];
      NSString *readToken = argsMap[@"readToken"];
      NSString *writeToken = argsMap[@"writeToken"];
      PLVVodSettings *settings = [PLVVodSettings settingsWithUserid:userID readtoken:readToken writetoken:writeToken secretkey:secretKey];
      settings.logLevel = PLVVodLogLevelAll;
      result([NSNumber numberWithBool:YES]);
  }
  else {
    result(FlutterMethodNotImplemented);
  }
}



// 点播SDK初始化
- (void)initSDKForLiveWithConfig:(NSString *)config aesKey:(NSString *)aesKey iv:(NSString *)iv{
    DLog(@"接收到的config >>>%@",config);
    if ([@"" isEqualToString:config]) return;
    //使用 PLVVodSettings 进行初始化
    NSError *error = nil;
    PLVVodSettings *settings = [PLVVodSettings settingsWithConfigString:config key:aesKey iv:iv error:&error];
    settings.logLevel = PLVVodLogLevelAll;
    settings.mutilAccount = YES;
}

@end



